package com.management.platform.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.management.platform.enums.LoginResultEnum;
import com.management.platform.model.Sim_information;
import com.management.platform.model.Sys_user;
import com.management.platform.service.InformationService;
import com.management.platform.service.UserLoginService;
import com.management.platform.util.Audience;
import com.management.platform.util.DateUtils;
import com.management.platform.util.JsonUtil;
import com.management.platform.util.JwtHelper;
import com.management.platform.util.LoginBaseComponent;
import com.management.platform.util.RedisUtil;
import com.management.platform.util.ResultCode;
import com.management.platform.util.VerifyUtil;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class UserLoginController{


  private static final Logger logger = LoggerFactory.getLogger(VerifyUtil.class);
  @Autowired
  private RedisUtil redisUtil;

  //@Resource
  //RedisTemplate<String, PlatformLoginUser> redisTemplate;

  @Autowired
  private UserLoginService userLoginService;

  @Autowired
  private ResultCode resultCode;

  @Autowired
  private DefaultKaptcha captchaProducer;

  @Autowired
  private Audience audience;

  @Autowired
  private LoginBaseComponent loginBaseComponent;
  //计数
  private int count;
  /**
   * 转到登录首页
   * @return
   */
  @RequestMapping("/login_index")
  public String index(){

    return "login_index";
  }



  /**
   * 生成token 并跳转登录
   * @return
   */
  @PostMapping("/login")
  public String login(@RequestParam("name") String name ,
      @RequestParam("pwd") String password,HttpServletRequest req,@RequestParam("vrifyCode")String vrifyCode) {

    if(name!=null&&password!=null) {
      /** 查询出角色 **/
      Sys_user user = userLoginService.selectByLogin(name, password);
      /** 获取存在session里的验证码字符串 **/
      String captchaId = (String) req.getSession().getAttribute("vrifyCode");
      /** 查询用户名密码 并判断验证码是否正确**/
        if (user != null && captchaId.equals(vrifyCode)) {
          /** 根据查询出的user_id 查询出role_id  **/
          Integer roleId = userLoginService.selectRoleId(user.getUserId()).getRoleId();
          /** 角色1,管理员 ; 2，普通用户 **/
          if (roleId == 1) {
            //生成token
            String jwtToken = JwtHelper.createJWT(name,
                password,
                audience.getClientId(),
                audience.getName(),
                audience.getExpiresSecond() * 1000,
                audience.getBase64Secret());
            String result_str = "bearer;" + jwtToken;
            System.out.println("token1:    " + jwtToken);
            resultCode.success(result_str); //存放登录成功信息

            /** 用redis存放登录信息  **/
            redisUtil.set("nameAdmin", name, 0);
            redisUtil.set("pwdAdmin", password, 0);

            /** 登录成功展示相关SIM卡信息**/
            loginBaseComponent.login_information();
            return "index";

          } else if (roleId == 2) {
            String jwtToken = JwtHelper.createJWT(name,
                password,
                audience.getClientId(),
                audience.getName(),
                audience.getExpiresSecond() * 1000,
                audience.getBase64Secret());

            String result_str = "bearer;" + jwtToken;
            System.out.println("token2:    " + jwtToken);
            resultCode.success(result_str);//存放登录成功信息
            System.out.println(resultCode.success(result_str).toString());
            /** 用redis存放登录信息  **/
            redisUtil.set("nameUser", name, 0);
            redisUtil.set("pwdUser", password, 0);
            /** 登录成功展示相关SIM卡信息**/
            loginBaseComponent.login_information();
            return "index";
          }
        }else if(user ==null ){//账号密码错误记录相关错误码
          resultCode.error(LoginResultEnum.USER_PASSWORD_ERROR);
          return "redirect:/login_index";
        }else if(!captchaId.equals(vrifyCode)){//验证码错误记录相关错误码
          resultCode.error(LoginResultEnum.VRIFYCODE_ERROR);
          return "redirect:/login_index";
        }
      }else{//当不输入账号密码时
        resultCode.error(LoginResultEnum.USER_PASSWORD_NOT_EMPTY);
        return "redirect:/login_index";
      }
    return "redirect:/login_index";
  }


  /**
   * 获取验证码 的 请求路径
   * @param httpServletRequest
   * @param httpServletResponse
   * @throws Exception
   */
  @RequestMapping("/defaultKaptcha")
  public void defaultKaptcha(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception{
    byte[] captchaChallengeAsJpeg = null;
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {
      //生产验证码字符串并保存到session中
      String createText = captchaProducer.createText();


      httpServletRequest.getSession().setAttribute("vrifyCode", createText);
      //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
      BufferedImage challenge = captchaProducer.createImage(createText);
      ImageIO.write(challenge, "jpg", jpegOutputStream);
    } catch (IllegalArgumentException e) {
      httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);
    httpServletResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream =
        httpServletResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
  }
}
